// language: java
package com.shopping.shoppingdemo.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Bean("writeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.write")
    public DataSource writeDataSource() {
        // 明确使用 HikariDataSource 并返回 javax\.sql\.DataSource
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("readDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.read")
    public DataSource readDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Primary
    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource(DataSource writeDataSource, DataSource readDataSource) {
        // 简化示例：如有自定义路由数据源请替换为你的实现
        org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource routing = new org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource() {
            @Override
            protected Object determineCurrentLookupKey() {
                return null; // 示例，实际按业务返回 key
            }
        };
        java.util.Map<Object, Object> map = new java.util.HashMap<>();
        map.put("write", writeDataSource);
        map.put("read", readDataSource);
        routing.setDefaultTargetDataSource(writeDataSource);
        routing.setTargetDataSources(map);
        routing.afterPropertiesSet();
        return routing;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dynamicDataSource) throws Exception {
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(dynamicDataSource);
        return fb.getObject();
    }
}
